# -*- coding: utf-8 -*-

import oss2
import os
from config import OSS_CONFIG
from util import *

OSS_AUTH = oss2.Auth(OSS_CONFIG['access_id'], OSS_CONFIG['access_key'])

def get_bucket_name_list():
    service = oss2.Service(OSS_AUTH, OSS_CONFIG['end_point'])
    bucket_name_list = []
    for b in service.list_buckets().buckets:
        bucket_name_list.append(b.name)
    return bucket_name_list

def get_folder_list_to_file(bucket_name, prefix, file_path):
    bucket = oss2.Bucket(OSS_AUTH, OSS_CONFIG['end_point'], bucket_name)
     
    flolder_list = []
    is_truncated = True  
    marker = '' 
    while is_truncated:
        res = bucket.list_objects(prefix=prefix, delimiter="/", marker=marker)
        for folder in res.prefix_list:
            flolder_list.append(folder)
        is_truncated = res.is_truncated
        marker = res.next_marker 
    write_list_to_file(flolder_list, file_path)

def delete_oss_object(bucket_name, object_name):
    bucket = oss2.Bucket(OSS_AUTH, OSS_CONFIG['end_point'], bucket_name)
    bucket.delete_object(object_name)

def download_oss_folder(bucket_name, prefix, local_path, delete_object_flag = False):
    bucket = oss2.Bucket(OSS_AUTH, OSS_CONFIG['end_point'], bucket_name)
    n = 0
    for obj in oss2.ObjectIterator(bucket, prefix=prefix):
        # 只处理文件对象（OSS通过/结尾标识目录）
        if False == obj.key.endswith('/'):
            local_file_path = os.path.join(local_path, obj.key.replace(':', ''))
            #print(local_file_path)
            os.makedirs(os.path.dirname(local_file_path), exist_ok=True) 
            oss2.resumable_download(bucket, obj.key, local_file_path)            
            n += 1
        if delete_object_flag:
            delete_oss_object(bucket_name, obj.key)
    print("%s下载完成，共下载了%d个文件" % (prefix, n))
    

if __name__ == '__main__':
    '''
    bl = get_bucket_name_list()
    write_list_to_file(bl, 'bucket_list.txt')
    '''
    bucket_name = 'sanbo'
    prefix = 'vivo_x20/'
    get_folder_list_to_file(bucket_name, prefix, 'folder_list.txt')
    #download_oss_folder(bucket_name, prefix, 'download')